package com.draven.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.draven.entity.OperationLog;
import com.draven.mapper.OperationLogMapper;
import com.draven.service.OperationLogService;
import com.draven.common.PageQuery;
import com.draven.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements OperationLogService {

    @Override
    public void saveLog(OperationLog log) {
        save(log);
    }
    
    @Override
    public Result<?> pageList(PageQuery pageQuery, OperationLog condition) {
        // 构建查询条件
        LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();
        if (condition.getUserId() != null) {
            wrapper.eq(OperationLog::getUserId, condition.getUserId());
        }
        if (condition.getModule() != null&& !condition.getModule().isEmpty()) {
            wrapper.eq(OperationLog::getModule, condition.getModule());
        }
        if (condition.getOperationType() != null&& !condition.getOperationType().isEmpty()) {
            wrapper.eq(OperationLog::getOperationType, condition.getOperationType());
        }
        if (condition.getStatus() != null) {
            wrapper.eq(OperationLog::getStatus, condition.getStatus());
        }
        wrapper.orderByDesc(OperationLog::getCreateTime);
        
        // 分页查询
        Page<OperationLog> page = page(new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize()), wrapper);
        return Result.success(page);
    }
    
    @Override
    public int cleanLogs(int days) {
        // 获取指定天数前的时间
        long time = System.currentTimeMillis() - (long) days * 24 * 60 * 60 * 1000;
        LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.lt(OperationLog::getCreateTime, new java.util.Date(time));
        return count(wrapper) > 0 ? baseMapper.delete(wrapper) : 0;
    }
} 